package com.example.myfultter

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.util.LruCache
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class MainActivity007 : AppCompatActivity() {
    
    private lateinit var imageView: ImageView
    private lateinit var loadButton: Button
    
    // 图片缓存
    private val imageCache: LruCache<String, Bitmap> by lazy {
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        val cacheSize = maxMemory / 8
        object : LruCache<String, Bitmap>(cacheSize) {
            override fun sizeOf(key: String, bitmap: Bitmap): Int {
                return bitmap.byteCount / 1024
            }
        }
    }
    
    // 示例图片URL
    private val imageUrl = "https://picsum.photos/800/600"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main007)
        
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        initViews()
        setupClickListener()
        
        // 自动加载图片
        loadImage()
    }
    
    private fun initViews() {
        imageView = findViewById(R.id.imageView)
        loadButton = findViewById(R.id.loadButton)
    }
    
    private fun setupClickListener() {
        loadButton.setOnClickListener {
            loadImage()
        }
    }
    
    private fun loadImage() {
        lifecycleScope.launch {
            try {
                val bitmap = loadImageWithCache(imageUrl)
                updateUI(bitmap, null)
            } catch (e: Exception) {
                Log.e("MainActivity007", "加载图片失败", e)
                updateUI(null, "加载图片失败: ${e.message}")
            }
        }
    }
    
    private suspend fun loadImageWithCache(url: String): Bitmap? = withContext(Dispatchers.IO) {
        // 检查缓存
        imageCache.get(url)?.let { cachedBitmap ->
            Log.d("MainActivity007", "从缓存加载图片")
            return@withContext cachedBitmap
        }
        
        // 缓存中没有，从网络加载
        Log.d("MainActivity007", "从网络加载图片: $url")
        val bitmap = downloadImage(url)
        
        // 将图片添加到缓存
        bitmap?.let { imageCache.put(url, it) }
        
        bitmap
    }
    
    private suspend fun downloadImage(url: String): Bitmap? = withContext(Dispatchers.IO) {
        var connection: HttpURLConnection? = null
        var inputStream: InputStream? = null
        
        try {
            var currentUrl = url
            var redirectCount = 0
            val maxRedirects = 5
            
            while (redirectCount < maxRedirects) {
                connection = URL(currentUrl).openConnection() as HttpURLConnection
                connection.apply {
                    requestMethod = "GET"
                    connectTimeout = 10000
                    readTimeout = 15000
                    setRequestProperty("User-Agent", "Android App")
                    doInput = true
                }
                
                val responseCode = connection.responseCode
                Log.d("MainActivity007", "HTTP响应码: $responseCode")
                
                if (responseCode in 300..399) {
                    // 处理重定向
                    val newUrl = connection.getHeaderField("Location")
                    if (newUrl != null) {
                        currentUrl = newUrl
                        redirectCount++
                        connection.disconnect()
                        continue
                    } else {
                        throw Exception("重定向失败，无法获取新URL")
                    }
                } else if (responseCode == 200) {
                    // 成功响应
                    inputStream = connection.inputStream.buffered()
                    return@withContext BitmapFactory.decodeStream(inputStream)
                } else {
                    throw Exception("HTTP错误: $responseCode")
                }
            }
            
            throw Exception("重定向次数过多")
            
        } catch (e: Exception) {
            Log.e("MainActivity007", "下载图片失败", e)
            throw e
        } finally {
            inputStream?.close()
            connection?.disconnect()
        }
    }
    
    private suspend fun updateUI(bitmap: Bitmap?, errorMessage: String?) = withContext(Dispatchers.Main) {
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap)
            Toast.makeText(this@MainActivity007, "图片加载成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this@MainActivity007, errorMessage ?: "加载失败", Toast.LENGTH_SHORT).show()
        }
    }
}